#include <surbasic/surbasic.h>
#include <iostream>

const std::string server = "https://open.surdoc.com";
const std::string user = "surdoctestooJUvF20@cc.cc";
const std::string password = "aA111111";

const int DMV_CHANGE_LIMIT = 1000;
const SDBasic::time::Timestamp BARRIER = SDBasic::time::Timestamp::FromTimeT(1);

class SurbasicDmvChangeTests {
 public:
  void GetFileChanges() {
    DoLogin();
    DmvChangeList temp;
    temp.reserve(DMV_CHANGE_LIMIT);
    std::string response;
    int offset = 0;

    while (true) {
      response.clear();
      temp.clear();

      bool success = SDBasic::GetFileChangeLists(
          token_key_, BARRIER, offset, DMV_CHANGE_LIMIT, false, &temp);
      if (!success) {
        std::cerr << "failed to get folder change lists";
        break;
      }

      offset += temp.size();
      for (size_t i = 0; i < temp.size(); ++i) {
        printf("FOLDER: %s - %s - %s\n", temp[i].id.c_str(),
               temp[i].parentid.c_str(), temp[i].name.c_str());
      }

      if (temp.size() < static_cast<size_t>(DMV_CHANGE_LIMIT)) break;
    }
  }

  void GetFolderChanges() {
    DoLogin();
    DmvChangeList temp;
    temp.reserve(DMV_CHANGE_LIMIT);
    std::string response;
    int offset = 0;

    while (true) {
      response.clear();
      temp.clear();

      bool success = SDBasic::GetFolderChangeLists(
          token_key_, BARRIER, offset, DMV_CHANGE_LIMIT, false, &temp);
      if (!success) {
        std::cerr << "failed to get folder change lists";
        break;
      }

      offset += temp.size();
      for (size_t i = 0; i < temp.size(); ++i) {
        printf("FOLDER: %s - %s - %s\n", temp[i].id.c_str(),
               temp[i].parentid.c_str(), temp[i].name.c_str());
      }

      if (temp.size() < static_cast<size_t>(DMV_CHANGE_LIMIT)) break;
    }
  }

 protected:
  void DoLogin() {
    SDBasic::AccessToken token;
    uint64_t result = SDBasic::Login(server, user, password, token);
    if (result == 0) {
      std::cerr << "failed to login";
      exit(-1);
    }
    token_key_ = result;

    bool ret = SDBasic::GetUserSpaceInfo(token_key_, uinfo_);
    if (!ret) {
      std::cerr << "failed to get user space info";
      exit(-1);
    }
  }

  void ExitIfFalse(bool result, const char* msg) {
    if (!result) {
      std::cerr << msg;
      exit(-1);
    }
  }

  uint64_t token_key_;
  UserSpaceInfo uinfo_;
};

int main() {
  SurbasicDmvChangeTests t;
  t.GetFolderChanges();
  t.GetFileChanges();
}
